<template>
    <label>
        <span>
            <input v-if="isGroup" type="radio" :value="label" v-model="form.model[formItem.prop]"/>
            <input v-else type="radio" :checked="currentValue" @change="change"/>
        </span>
        {{label}}
    </label>
</template>

<script>
    import Emitter from '../../mixins/emitter.js'
    import { findComponentUpward } from "../../utils/assist"

    export default {
        name: 'iRadio',
        mixins: [Emitter],
        inject: ['form', 'formItem'],
        props: {
            label: {
                type: String,
                default: ''
            },
            value: {
                type: [String, Number, Boolean]
            },
            trueValue: {
                type: [String, Number, Boolean],
                default: true
            },
            falseValue: {
                type: [String, Number, Boolean],
                default: false
            }
        },
        data() {
            return {
                isGroup: false,
                // model: null, // 用于group
                currentValue: false
            }
        },
        created() {
            this.init()
        },
        methods: {
            init() {
                this.parent = findComponentUpward(this, 'iRadioGroup')
                if (this.parent) {
                    this.isGroup = true
                } else {
                    this.updateModel()
                }
            },
            change(e) {
                this.$emit('input', value ? this.trueValue : this.falseValue) // 一个支持v-model的组件，一定要有prop value和emit input 或者change
                const value = e.target.checked
                this.currentValue = value

                if (this.isGroup) {
                    this.parent.change()
                } else {
                    this.$emit('on-change', value)
                    this.dispatch('iFormItem', 'on-form-change', value)
                }
            },
            updateModel() {
                this.currentValue = this.value === this.trueValue
            }
        },
        watch: {
            value() {
                if (this.value === this.trueValue || this.value === this.falseValue) {
                    this.updateModel()
                } else {
                    throw 'value should be trueValue or falseValue'
                }
            }
        },
        computed: {
            model() {
                return this.form.model.radio
            }
        },
    }
</script>
